package com.yyg.boot.web;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.*;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/5/17
 * @Description Description
 */
@SuppressWarnings("NRAvoidUseTimer")
@RestController
public class TaskController {

    @GetMapping("/timer")
    public String timerTask(){
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println("task  run:"+ new Date());
            }
        };
        Timer timer = new Timer();
        //安排指定的任务在指定的时间开始进行重复的固定延迟执行。这里是每3秒执行一次
        timer.schedule(timerTask,10,3000);
        return "success";
    }

    @GetMapping("/scheduler")
    public String scheduler(){
        //尽量不要采用Executors方式创建ScheduledExecutorService,可能会造成耗费内存,甚至OOM
        //ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder()
                        .namingPattern("schedule-pool-%d")
                        .daemon(true)
                        .build());
        // 参数：1.任务体;2.首次执行的延时时间;3.任务执行间隔;4.间隔时间单位.
        executorService.scheduleAtFixedRate(()->System.out.println("定时任务:"+new Date()), 0, 3, TimeUnit.SECONDS);
        return "success";
    }

}
